use std::lazy::SyncLazy;

use ggez::graphics::*;
use ggez::Context;
use ggez::GameResult;

use crate::logic::unit;
use crate::view::{FrameNumber, TILE_SIZE};

use super::UnitDrawable;

const DOT_SIZE: f32 = TILE_SIZE / 16.0;

fn dot(dot_x: u32, dot_y: u32, size: u32) -> Rect {
    let x = DOT_SIZE * (dot_x as f32);
    let y = DOT_SIZE * (dot_y as f32);
    let w = DOT_SIZE * (size as f32);
    let h = DOT_SIZE * (size as f32);
    Rect::new(x, y, w, h)
}

static HEAD_POS_1: SyncLazy<Rect> = SyncLazy::new(|| dot(7, 6, 2));
static HEAD_POS_2: SyncLazy<Rect> = SyncLazy::new(|| dot(7, 5, 2));
static HEAD_COLOR: SyncLazy<Color> = SyncLazy::new(|| Color::from_rgba(244, 244, 0, 255));

static LEFT_WING_POS_1: SyncLazy<Rect> = SyncLazy::new(|| dot(2, 5, 2));
static LEFT_WING_POS_2: SyncLazy<Rect> = SyncLazy::new(|| dot(2, 9, 2));
static RIGHT_WING_POS_1: SyncLazy<Rect> = SyncLazy::new(|| dot(12, 5, 2));
static RIGHT_WING_POS_2: SyncLazy<Rect> = SyncLazy::new(|| dot(12, 9, 2));
static WING_COLOR: SyncLazy<Color> = SyncLazy::new(|| Color::from_rgba(215, 215, 215, 255));

impl UnitDrawable for unit::LittleFairy {
    fn as_drawable(&self, frame_number: FrameNumber, ctx: &mut Context) -> GameResult<Mesh> {
        let frame_60 = frame_number % 120;

        if frame_60 < 80 {
            MeshBuilder::new()
                .rectangle(
                    DrawMode::Fill(FillOptions::DEFAULT),
                    *HEAD_POS_1,
                    *HEAD_COLOR,
                )?
                .rectangle(
                    DrawMode::Fill(FillOptions::DEFAULT),
                    *LEFT_WING_POS_1,
                    *WING_COLOR,
                )?
                .rectangle(
                    DrawMode::Fill(FillOptions::DEFAULT),
                    *RIGHT_WING_POS_1,
                    *WING_COLOR,
                )?
                .build(ctx)
        } else {
            MeshBuilder::new()
                .rectangle(
                    DrawMode::Fill(FillOptions::DEFAULT),
                    *HEAD_POS_2,
                    *HEAD_COLOR,
                )?
                .rectangle(
                    DrawMode::Fill(FillOptions::DEFAULT),
                    *LEFT_WING_POS_2,
                    *WING_COLOR,
                )?
                .rectangle(
                    DrawMode::Fill(FillOptions::DEFAULT),
                    *RIGHT_WING_POS_2,
                    *WING_COLOR,
                )?
                .build(ctx)
        }
    }
}
